#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<stdlib.h>
#include<string.h>
#include<errno.h>
#include<arpa/inet.h>
#include<unistd.h>
#define MSG_STR "Welcome to LiYi studio server"

int main(int argc,char **argv)
{
	int 			sockfd=-1;
	int 			clifd=-1;
	int 			rv=-1;
	int 			port=0;
	int 			on=1;
	socklen_t		len;
	struct sockaddr_in	servaddr;
	struct sockaddr_in	cliaddr;
	char			buf[1024];

	if(argc<2)
	{
		printf("Program usage : %s [PORT]\n",argv[0]);
		return -1;
	}
	port=atoi(argv[1]);
	
	//创建SOCKET
	sockfd=socket(AF_INET,SOCK_STREAM,0);
	if(sockfd<0)
	{
		printf("Create a socket[%d] failure: %s\n",sockfd,strerror(errno));
		return -1;
	}
	printf("Create socket[%d] successfully!\n",sockfd);

	setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,&on,sizeof(on));


	//bind
	memset(&servaddr,0,sizeof(servaddr));
	servaddr.sin_family=AF_INET;
	servaddr.sin_port=htons(port);

	//将字符串转成网络字序
	servaddr.sin_addr.s_addr=htonl(INADDR_ANY);
	rv=bind(sockfd,(struct sockaddr *)&servaddr,sizeof(servaddr));
	if(rv<0)
	{
		printf("Socket[%d] bind on port[%d] failure: %s\n",sockfd,port,strerror(errno));
		return -2;
	}



	//sockfd,backlog
	listen(sockfd,13);
	printf("Start to listen on port [%d]!\n",port);


	while(1)
	{	
		printf("Start accept new client incoming\n");

		clifd=accept(sockfd,(struct sockaddr *)&cliaddr,&len);
		if(clifd<0)
		{
			printf("Accept new client failure:%s\n",strerror(errno));
			continue;
		}
		printf("Accept new client[%s:%d] successfully!\n",inet_ntoa(cliaddr.sin_addr),ntohs(cliaddr.sin_port));
	

		//读 服务器端读的是客户端的fd  注意：这里读的是客户端的fd
		memset(buf,0,sizeof(buf));
		rv=read(clifd,buf,sizeof(buf));
		if(rv==0)
		{
			printf("Sockfd[%d] get disconnected!\n",clifd);
			close(clifd);
			continue;
		}
		else if(rv<0)
		{
			printf("Read data from client sockfd[%d] failure:%s\n",clifd,strerror(errno));
			close(clifd);
			continue;
		}
		else if(rv>0)
		{
			printf("read data %d bytes from client %s  successfully!\n",rv,buf);
		}
		
		//写 这里也是写的客户端的fd
		rv=write(clifd,MSG_STR,sizeof(MSG_STR));
		if(rv<0)
		{
			printf("Write to client by sockfd[%d] failure:%s\n",clifd,strerror(errno));
			return -3;
		}
		printf("Write to client by sockfd[%d] successfully!\n",sockfd);

	
	}
	close(sockfd);
}

		
